# encoding: utf-8

from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models

from app.models.area import Area
from app.utils import PROVINCE_CHOICES, CITY_CHOICES, AREA_CHOICES


class FMUserManager(BaseUserManager):
    def create_user(self, username, realname=None, identity=None,
                    email=None, date_of_birth=None, password=None):
        if not username:
            raise ValueError(u'用户名不能为空')

        user = self.model(
            username=username,
            realname=realname,
            identity=identity,
            email=self.normalize_email(email),
            date_of_birth=date_of_birth
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, realname=None, identity=None,
                         email=None, date_of_birth=None, password=None):
        user = self.create_user(
            username, realname, identity,
            email, date_of_birth, password
        )
        user.is_superuser = True
        user.save(using=self._db)
        return user


USER_TYPE_ADMIN = 0
USER_TYPE_SALES = 1
USER_TYPE_USER = 2
UserType = [
    (USER_TYPE_ADMIN, u'管理员'),
    (USER_TYPE_SALES, u'销售'),
    (USER_TYPE_USER, u'用户'),
]


class FMUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=30, unique=True, verbose_name=u'用户名')
    realname = models.CharField(max_length=30, null=True, blank=True, verbose_name=u'真实姓名')
    identity = models.CharField(max_length=18, null=True, blank=True, unique=True, verbose_name=u'身份证号')
    email = models.EmailField(verbose_name=u'邮箱', max_length=255, null=True, blank=True)
    password = models.CharField(max_length=128, verbose_name=u'密码')
    date_of_birth = models.DateField(null=True, blank=True, verbose_name=u'生日')
    province = models.IntegerField(choices=PROVINCE_CHOICES, null=True, blank=True, verbose_name=u'省', default=32)
    city = models.IntegerField(choices=CITY_CHOICES, null=True, blank=True, verbose_name=u'市/镇', default=3201)
    area = models.IntegerField(choices=AREA_CHOICES, null=True, blank=True, verbose_name=u'区/乡', default=320101)
    address = models.TextField(verbose_name=u'住址', default='', null=True, blank=True)
    merchant_name = models.CharField(max_length=100, null=True, blank=True, verbose_name=u'商户名称', default='')
    sales = models.ForeignKey('self', related_name='users', null=True, blank=True, verbose_name=u'销售')
    sales_area = models.ForeignKey(Area, related_name='sales', verbose_name=u'销售区域', null=True, blank=True)
    user_type = models.IntegerField(choices=UserType, default=USER_TYPE_USER, verbose_name=u'用户类型')

    is_active = models.BooleanField(default=True, verbose_name=u'是否可用')

    objects = FMUserManager()

    USERNAME_FIELD = 'username'

    # REQUIRED_FIELDS = ['realname', 'province', 'city', 'area', 'address', 'merchant_name']

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def __str__(self):
        if self.user_type == USER_TYPE_USER:
            return self.merchant_name
        if self.user_type == USER_TYPE_SALES:
            if self.realname:
                return self.realname
        return self.username

    def has_group(self, group):
        if not self.is_active:
            return False
        if self.is_superuser:
            return True
        if not hasattr(self, '_group_cache'):
            self._group_cache = set([g.name for g in self.groups.all()])
        return group in self._group_cache

    @property
    def is_staff(self):
        return self.is_superuser or self.user_type == USER_TYPE_SALES or self.user_type == USER_TYPE_ADMIN

    class Meta:
        verbose_name = u'用户'
        verbose_name_plural = u'用户'


class UserAccount(models.Model):
    user = models.OneToOneField(FMUser, related_name='account', verbose_name=u'用户')
    balance = models.IntegerField(verbose_name=u'账户余额')

    def __str__(self):
        return '[%s：%d(分)]' % (self.user, self.balance)

    class Meta:
        verbose_name = u'用户账户'
        verbose_name_plural = u'用户账户'
